//
//  MYGeneralShareView.m
//  JQLive
//
//  Created by Bruce on 2020/3/9.
//  Copyright © 2020 JQLive. All rights reserved.
//

#import "MYGeneralShareView.h"
#import "MYShareCollectionViewCell.h"
#import <objc/message.h>

NSString const *MYShareItemTitleKey = @"title";
NSString const *MYShareItemIconKey = @"icon";
NSString const *MYShareItemActionKey = @"action";

@interface MYGeneralShareView ()<UICollectionViewDataSource,UICollectionViewDelegate,UICollectionViewDelegateFlowLayout>
{
    UIView *my_mainView;
    UILabel *my_titleLabel;
    NSInteger my_saveBottom;
}
@property (nonatomic, copy) MYGeneralShareViewCompletion completion;
@property (nonatomic,strong) NSArray *my_itemArray;
@property (nonatomic,strong) UICollectionView* my_collectionView;
@end

@implementation MYGeneralShareView

- (NSArray *)my_itemArray
{
    if (!_my_itemArray)
    {
        _my_itemArray = [self getDataWithTypeArray:@[
            @(MYShareTypeGroup),
            @(MYShareTypeFriendCircle),
            @(MYShareTypeFriend),
            @(MYShareTypeQQ),
            @(MYShareTypeQzone),
            @(MYShareTypeWeibo),
            @(MYShareTypeCopyLink),
//            @(MYShareTypeDelete),
        ]];
    }
    return _my_itemArray;
}

- (UICollectionView *)my_collectionView
{
    if (!_my_collectionView)
    {
        UICollectionViewFlowLayout* flowLayout = [[UICollectionViewFlowLayout alloc] init];
        [flowLayout setScrollDirection:UICollectionViewScrollDirectionVertical];
        flowLayout.minimumLineSpacing = 5;
        flowLayout.minimumInteritemSpacing = 5;
        flowLayout.sectionInset = UIEdgeInsetsMake(0, 10, 0, 10);
        flowLayout.itemSize = CGSizeMake((SCREEN_WIDTH-40)/4, 80);
        
        _my_collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:flowLayout];
        [_my_collectionView registerClass:[MYShareCollectionViewCell class] forCellWithReuseIdentifier:@"MYShareCollectionViewCell"];
        _my_collectionView.backgroundColor = [UIColor whiteColor];
        _my_collectionView.showsVerticalScrollIndicator = NO;
        _my_collectionView.scrollsToTop = NO;
        _my_collectionView.dataSource = self;
        _my_collectionView.delegate = self;
        _my_collectionView.layer.cornerRadius = 8;
        _my_collectionView.clipsToBounds = YES;
    }
    return _my_collectionView;
}

- (void)showWithNav:(UINavigationController *)nav
          itemArray:(NSArray *)array
         completion:(MYGeneralShareViewCompletion)completion
{
    [[[[UIApplication sharedApplication] delegate] window] addSubview:self];
    self.completion = completion;
    
    if (array.count > 0)
    {
        self.my_itemArray = [self getDataWithTypeArray:array];
        [self.my_collectionView reloadData];
    }
    [self freashFrame];
    [UIView animateWithDuration:0.3 animations:^{
        self->my_mainView.transform = CGAffineTransformTranslate(self->my_mainView.transform, 0, -self->my_mainView.bounds.size.height);
    } completion:^(BOOL finished) {
    }];
}

- (instancetype)initWithFrame:(CGRect)frame
{
    frame = CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT);
    
    if(self = [super initWithFrame:frame])
    {
        [self layout];
    }
    
    return self;
}

- (void)layout
{
    self.backgroundColor = [UIColor colorWithWhite:0 alpha:0.4];
    
    my_saveBottom = INTERFACE_IS_IPHONEX ? 34 : 0;
    
    my_mainView = [[UIView alloc] initWithFrame:CGRectMake(0, SCREEN_HEIGHT-my_saveBottom-330, SCREEN_WIDTH, 330+my_saveBottom)];
    my_mainView.backgroundColor = [UIColor whiteColor];
    my_mainView.clipsToBounds = YES;
    [self addSubview:my_mainView];
    [my_mainView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(0);
        make.bottom.mas_equalTo(0);
        make.width.mas_equalTo(SCREEN_WIDTH);
        make.height.mas_equalTo(330+my_saveBottom);
    }];
    
    
    my_titleLabel = [[UILabel alloc] init];
    my_titleLabel.font = [UIFont systemFontOfSize:16];
    my_titleLabel.textColor = MY_Text_Color_Theme1;
    my_titleLabel.text = @"分享到";
    [my_mainView addSubview:my_titleLabel];
    
    UIButton *my_cancelButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [my_cancelButton setTitle:@"取消" forState:0];
    my_cancelButton.titleLabel.font = [UIFont systemFontOfSize:18];
    [my_cancelButton setTitleColor:MY_ColourMatchingSpecifications_Theme1 forState:0];
    my_cancelButton.backgroundColor = MY_ColourMatchingSpecifications_VCBack;
    [my_cancelButton addTarget:self action:@selector(cancelButtonTouchUpInside:) forControlEvents:UIControlEventTouchUpInside];
    [my_mainView addSubview:my_cancelButton];
    
    [my_titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(self->my_mainView);
        make.top.equalTo(@(MY_Padding));
    }];
    
    [my_cancelButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.height.equalTo(@60);
        make.left.right.equalTo(self->my_mainView);
        make.bottom.equalTo(@(-my_saveBottom));
    }];
    
    [my_mainView addSubview:self.my_collectionView];
    
    [self.my_collectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.left.equalTo(self->my_mainView);
        make.bottom.equalTo(my_cancelButton.mas_top).offset(-10);
        make.top.equalTo(self->my_titleLabel.mas_bottom).offset(34);
    }];
    
    //设置上面两个圆角
    UIBezierPath* maskPath = [UIBezierPath bezierPathWithRoundedRect:my_mainView.bounds byRoundingCorners:UIRectCornerTopLeft | UIRectCornerTopRight cornerRadii:CGSizeMake(12, 12)];
    CAShapeLayer* maskLayer = [[CAShapeLayer alloc] init];
    maskLayer.frame = my_mainView.bounds;
    maskLayer.path = maskPath.CGPath;
    my_mainView.layer.mask = maskLayer;
    
    my_mainView.transform = CGAffineTransformTranslate(my_mainView.transform, 0, my_mainView.bounds.size.height);
}

- (void)freashFrame
{
    NSInteger lineMax = 4;//最多一行几个
    NSInteger count = self.my_itemArray.count;
    NSInteger row = count/lineMax + ((count%lineMax)>0?1:0);
    CGFloat itemHeigh = 85;
    CGFloat mainHeight =  150 + row*itemHeigh;
    [my_mainView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.height.mas_equalTo(mainHeight +my_saveBottom);
    }];
    
    DLog(@"%@",my_mainView);
}

#pragma mark - UICollectionView delgate
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView
{
    return 1;
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
    return self.my_itemArray.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    MYBaseCollectionViewCell* cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"MYShareCollectionViewCell" forIndexPath:indexPath];
    
    [cell updateContent:self.my_itemArray[indexPath.row]];
    return cell;
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *actionString = self.my_itemArray[indexPath.row][MYShareItemActionKey];
    if(actionString)
    {
        SEL action = NSSelectorFromString(actionString);
        if([self respondsToSelector:action])
        {
            void (* my_objc_msgSend)(id,SEL,id) = (void (*)(id,SEL,id))objc_msgSend;
            my_objc_msgSend(self,action,indexPath);
        }
    }
}

/**
 *  好友/群组
 *
 *  @param path 行路径
 */
- (void)didSelectGroupWithIndexPath:(NSIndexPath *)path
{
    [self selectType:MYShareTypeGroup];
}

/**
 *  朋友圈
 *
 *  @param path 行路径
 */
- (void)didSelectCircleFriendsWithIndexPath:(NSIndexPath *)path
{
    [self selectType:MYShareTypeFriendCircle];
}

/**
 *  微信好友
 *
 *  @param path 行路径
 */
- (void)didSelectWeChatWithIndexPath:(NSIndexPath *)path
{
    [self selectType:MYShareTypeFriend];
}

/**
 *  QQ
 *
 *  @param path 行路径
 */
- (void)didSelectQQWithIndexPath:(NSIndexPath *)path
{
    [self selectType:MYShareTypeQQ];
}

/**
*  QQ空间
*
*  @param path 行路径
*/
- (void)didSelectQzoneWithIndexPath:(NSIndexPath *)path
{
    [self selectType:MYShareTypeQzone];

}
/**
 *  微博
 *
 *  @param path 行路径
 */
- (void)didSelectSinaWithIndexPath:(NSIndexPath *)path
{
    [self selectType:MYShareTypeWeibo];
}

/**
 *  复制链接
 *
 *  @param path 行路径
 */
- (void)didSelectCopyLinkWithIndexPath:(NSIndexPath *)path
{
    UIPasteboard* pasteboard = [UIPasteboard generalPasteboard];
    pasteboard.string = @"";
    
    [self dismiss];
}

/**
 *  删除
 *
 *  @param path 行路径
 */
- (void)didSelectDeleteWithIndexPath:(NSIndexPath *)path
{
   [self selectType:MYShareTypeDelete];

    [self dismiss];
}

/// 投诉
/// @param path 行路径
- (void)didSelectComplainWithIndexPath:(NSIndexPath *)path
{
    [self selectType:MYShareTypeComplain];
}

/// 不感兴趣
/// @param path 行路径
- (void)didSelectDontLikeWithIndexPath:(NSIndexPath *)path
{
    [self selectType:MYShareTypeDontLike];
}

/// 不感兴趣
/// @param path 行路径
- (void)didSelectPermissionSettingWithIndexPath:(NSIndexPath *)path
{
    [self selectType:MYShareTypePermissionSetting];
}
//
- (void)selectType:(MYShareType)type
{
    if (self.completion)
    {
        self.completion(self, type);
    }
    [self dismiss];
}

#pragma mark- 自定义方法

- (void)cancelButtonTouchUpInside:(UIButton *)sender
{
    [self dismiss];
}

- (void)dismiss
{
    //点击关闭
    [UIView animateWithDuration:0.20 animations:^{
        self->my_mainView.transform = CGAffineTransformTranslate(self->my_mainView.transform, 0, self->my_mainView.bounds.size.height);
        
    } completion:^(BOOL finished) {
        [UIView animateWithDuration:0.20 animations:^{
            self.alpha = 0.0;
        } completion:^(BOOL finished) {
            self.hidden = YES;
            [self removeFromSuperview];
        }];
    }];
}

- (NSArray *)getDataWithTypeArray:(NSArray *)typeArray
{
    NSMutableArray *data = [[NSMutableArray alloc] init];
     for (NSNumber *item in typeArray) {
         MYShareType type = [item integerValue];
         [data addObject:[self getDataWithType:type]];
    }
    return  data;
}

- (NSDictionary *)getDataWithType:(MYShareType)type
{
    NSDictionary *dict;
    switch (type) {
        
        case MYShareTypeGroup:
        {
            dict = @{MYShareItemTitleKey:@"好友/群组",
                     MYShareItemIconKey:@"common_Share_Group",
                     MYShareItemActionKey:@"didSelectGroupWithIndexPath:"};
        }
            break;
        case MYShareTypeFriendCircle:
        {
            dict = @{MYShareItemTitleKey:@"朋友圈",
                     MYShareItemIconKey:@"common_Share_FriendCircle",
                     MYShareItemActionKey:@"didSelectCircleFriendsWithIndexPath:"};
        }
            break;
        case MYShareTypeFriend:
        {
            dict = @{MYShareItemTitleKey:@"微信好友",
                     MYShareItemIconKey:@"common_Share_Weachat",
                     MYShareItemActionKey:@"didSelectWeChatWithIndexPath:"};
        }
            break;
        case MYShareTypeQQ:
        {
            dict = @{MYShareItemTitleKey:@"QQ好友",
                     MYShareItemIconKey:@"common_Share_QQ",
                     MYShareItemActionKey:@"didSelectQQWithIndexPath:"};
        }
            break;
        case MYShareTypeQzone: {
            dict = @{MYShareItemTitleKey:@"QQ空间",
            MYShareItemIconKey:@"common_Share_Qzone",
            MYShareItemActionKey:@"didSelectQzoneWithIndexPath:"};
            break;
        }
        case MYShareTypeWeibo:
        {
            dict = @{MYShareItemTitleKey:@"新浪微博",
                     MYShareItemIconKey:@"common_Share_Sina",
                     MYShareItemActionKey:@"didSelectSinaWithIndexPath:"};
        }
            break;
        case MYShareTypeCopyLink:
        {
            dict = @{MYShareItemTitleKey:@"复制链接",
                     MYShareItemIconKey:@"common_Share_CopyLink",
                     MYShareItemActionKey:@"didSelectCopyLinkWithIndexPath:"};
        }
            break;
        case MYShareTypeDelete:
        {
            dict = @{MYShareItemTitleKey:@"删除",
                     MYShareItemIconKey:@"common_Share_Delete",
                     MYShareItemActionKey:@"didSelectDeleteWithIndexPath:"};
        }
            break;
        case MYShareTypeComplain:
        {
            dict = @{MYShareItemTitleKey:@"举报",
                     MYShareItemIconKey:@"common_Share_Complain",
                     MYShareItemActionKey:@"didSelectComplainWithIndexPath:"};
        }
            break;
            
        case MYShareTypeDontLike: {
            dict = @{MYShareItemTitleKey:@"不感兴趣",
            MYShareItemIconKey:@"common_Share_DontLike",
            MYShareItemActionKey:@"didSelectDontLikeWithIndexPath:"};
            break;
        }
            
        case MYShareTypePermissionSetting: {
            dict = @{MYShareItemTitleKey:@"权限设置",
            MYShareItemIconKey:@"common_Share_PermissionSetting",
            MYShareItemActionKey:@"didSelectPermissionSettingWithIndexPath:"};
            break;
        }
    }
    
    return dict;
}

@end
